package servlet;


import bean.model.marketUser.MarketUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import service.AuthService;
import service.AuthServiceImpl;
import servlet.util.PageVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/auth/login")
public class Auth extends HttpServlet {
    //这个地方是路由

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //这个地方是路由，路由有传参，用户名和密码
        //通过post请求体传入的参数
        //将对应参数转换为Map对象
        //先获取请求行的内容
        StringBuffer reqInfo=new StringBuffer();
        //先正确读取传入内容
        String temp="";
        while ((temp=req.getReader().readLine())!=null){
            reqInfo.append(temp);
        }

        ObjectMapper objectMapper = new ObjectMapper();
        Map results=objectMapper.readValue(new String(reqInfo),Map.class);

        //先去查询数据库，看是否存在当前的记录
        //查询数据库要调用service层
        AuthService authService=new AuthServiceImpl();
        List<MarketUser> marketUser=authService.getMarketUser((String) results.get("userName"), (String) results.get("password"));
        PageVO<String> pageVO=new PageVO<>();
        if (!marketUser.isEmpty()){
            //能到这里说明查询成功了
            HttpSession session=req.getSession();
            session.setAttribute("marketUserId",marketUser.get(0).getId());
            pageVO.setObject("成功");
            pageVO.setErrno(0);
        }else {
            //在这里说明查询失败了,这里主要是操作返回了什么
            pageVO.setErrno(1);
            pageVO.setErrmsg("没找到对应信息 ");
        }

        resp.getWriter().println(objectMapper.writeValueAsString(pageVO));


        System.out.println("111");


    }
}
